package com.xindaoapp.happypet.activity;

import java.text.DecimalFormat;
import java.util.LinkedList;
import java.util.List;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.api.AddClient;
import com.xindaoapp.happypet.api.Address;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.Good;
import com.xindaoapp.happypet.bean.SerachGood;
import com.xindaoapp.happypet.shop.ui.ProductDetailActivity;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshBase;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshListView;

/**
 * 商品列表
 * 
 * @author Yangqing
 * 
 */
public class CatListItem extends BaseLoadAnimationAcitivity implements OnClickListener {
    @ViewInject(R.id.cat_goods_list)
    private PullToRefreshListView cat_goods_list;
    @ViewInject(R.id.no_result)
    private RelativeLayout no_result;

    @ViewInject(R.id.tittle_shop_cancel)
    private ImageView tittle_shop_cancel;
    @ViewInject(R.id.tittle_shop_content)
    private TextView tittle_shop_content;

    private int currentPosition = -1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_catitem);
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);
        if (!TextUtils.isEmpty(getIntent().getStringExtra("catID"))) {
            catID = getIntent().getStringExtra("catID");
        }
        if (!TextUtils.isEmpty(catName = getIntent().getStringExtra("catName"))) {
            catName = getIntent().getStringExtra("catName");
        }
        tittle_shop_content.setText(catName);
        initClick();
        initList();
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (adapter != null && currentPosition != -1) {
            goods.get(currentPosition).setSold_number(
                    Integer.parseInt(goods.get(currentPosition).getSold_number()) + 1 + "");
            adapter.notifyDataSetChanged();
        }
    }

    private void initClick() {
        tittle_shop_cancel.setOnClickListener(this);
    }

    private final LinkedList<Good> goods = new LinkedList<Good>();
    private GoodSerachAdapter adapter;
    private String catID;
    private String catName;
    private int page;

    // private boolean isConnectNetWork = false;//网络连接是否正常
    private void initList() {
        page = 1;
        fillData(page);
        cat_goods_list.setPullLoadEnabled(true);
        cat_goods_list.setPullRefreshEnabled(true);
        cat_goods_list.setOnRefreshListener(new OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                goods.clear();
                page = 1;
                fillData(page);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                page++;
                fillData(page);
            }
        });


        cat_goods_list.getRefreshableView().setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    Intent intent = new Intent(CatListItem.this, ProductDetailActivity.class);
                    intent.putExtra(Constants.KEY_GOODS_ID, goods.get(position).getGoods_id());
                    startActivity(intent);
                    currentPosition = position;
                    // Intent intent = new Intent(CatListItem.this, ProductDetailActivity1.class);
                    // intent.putExtra("productId", (goods.get(position).getGoods_id()));
                    // startActivity(intent);
                    // goods.get(position).setSold_number(
                    // Integer.parseInt(goods.get(position).getSold_number()) + 1 + "");

                    ViewHolder viewholder = (ViewHolder) view.getTag();
                    viewholder.good_sell.setText(Integer.parseInt(goods.get(position)
                            .getSold_number()) + 1 + "");

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        setLastUpdateTime();
    }

    private boolean isFirst = true;

    private void fillData(int page) {
        RequestParams params = new RequestParams();
        params.put("page", String.valueOf(page));
        if (!TextUtils.isEmpty(catID)) {
            params.put("catID", catID);
        } else {
            if (!TextUtils.isEmpty(catName)) {
                params.put("catName", catName);
            }
        }
        params.put("pageSize", Address.PAGECOMMONSIZE);
        // final ProgressHUD ProgressDialog = ProgressHUD.show(this, "正在加载...", true, true, null);
        AddClient.get(Address.GOODSLIST, params, new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                try {
                    isFirst = false;
                    SerachGood parse = JSON.parseObject(content, SerachGood.class);
                    if (parse.getStatus().equals("1")) {
                        if (!parse.getMsg().equals("暂无数据！")) {
                            if (Integer.parseInt(parse.getData().getCount()) > 0) {
                                cat_goods_list.setVisibility(View.VISIBLE);
                                List<Good> info = parse.getData().getInfo();
                                goods.addAll(info);
                                if (adapter == null) {
                                    adapter = new GoodSerachAdapter(goods);
                                    cat_goods_list.getRefreshableView().setAdapter(adapter);
                                    adapter.notifyDataSetChanged();
                                } else {
                                    adapter.notifyDataSetChanged();
                                }

                                HappyPetApplication.mHandler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        onDataArrived(true);
                                    }
                                }, 1000);
                            } else {
                                onDataArrivedEmpty();
                                Toast.makeText(getApplicationContext(), parse.getMsg(),
                                        Toast.LENGTH_SHORT).show();
                            }
                        } else if (parse.getMsg().equals("暂无数据！") && goods.size() <= 0) {
                            no_result.setVisibility(View.VISIBLE);
                            cat_goods_list.setVisibility(View.GONE);
                        }

                    }
                    onLoaded();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // onLoaded();
                super.onSuccess(statusCode, content);
            }

            @Override
            public void onFailure(Throwable error, String content) {
                if (isFirst) {
                    onDataArrived(false);
                    SetOnLoadFailListener(new OnLoadFailListener() {
                        @Override
                        public void onLoadFail() {
                            fillData(1);
                        }
                    });
                } else {
                    onDataArrived(true);
                }
                super.onFailure(error, content);
            }
        });
        setLastUpdateTime();
    }

    private void onLoaded() {
        cat_goods_list.onPullDownRefreshComplete();
        cat_goods_list.onPullUpRefreshComplete();
    }

    private void setLastUpdateTime() {
        String text = CommonUtil.formatPullToRefreshDate();
        cat_goods_list.setLastUpdatedLabel(text);
    }

    private class GoodSerachAdapter extends BaseAdapter {
        private final List<Good> goods2;

        public GoodSerachAdapter(List<Good> goods2) {
            super();
            this.goods2 = goods2;
        }

        @Override
        public int getCount() {
            return goods2.size();
        }

        @Override
        public Object getItem(int position) {
            return goods2.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = View.inflate(CatListItem.this, R.layout.good_common_item, null);
                holder.good_pic = (ImageView) convertView.findViewById(R.id.good_pic);
                holder.good_name = (TextView) convertView.findViewById(R.id.good_name);
                holder.good_shop_price = (TextView) convertView.findViewById(R.id.good_shop_price);
                holder.good_market_price =
                        (TextView) convertView.findViewById(R.id.good_market_price);
                holder.good_sell = (TextView) convertView.findViewById(R.id.good_sell);
                holder.good_surplus = (TextView) convertView.findViewById(R.id.good_surplus);
                holder.goods_comment = (TextView) convertView.findViewById(R.id.goods_comment);
                holder.good_dazhe = (TextView) convertView.findViewById(R.id.good_dazhe);

                holder.good_sell.setTag(position);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.good_name.setText(goods2.get(position).getGoods_name());
            holder.good_name.setText(goods2.get(position).getGoods_name());
            holder.good_shop_price.setText(goods2.get(position).getShop_price());
            holder.good_market_price.setText("￥" + goods2.get(position).getMarket_price());
            holder.good_market_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            holder.good_sell.setText(goods2.get(position).getSold_number());
            holder.good_surplus.setText(goods2.get(position).getGoods_number());
            holder.goods_comment.setText(goods2.get(position).getComment_percent());

            ImageLoader.getInstance().displayImage(goods2.get(position).getGoods_thumb(),
                    holder.good_pic);

            float a =
                    (Float.valueOf(goods2.get(position).getShop_price()) / Float.valueOf(goods2
                            .get(position).getMarket_price())) * 10;
            holder.good_dazhe.setText(formatDaZhe(a) + "折");
            return convertView;
        }

    }

    private String formatDaZhe(Float a) {
        DecimalFormat df = new DecimalFormat(".0");
        return df.format(a);
    }


    public class ViewHolder {
        ImageView good_pic;
        TextView good_name;
        TextView good_shop_price;
        TextView good_market_price;
        TextView good_sell;
        TextView good_surplus;
        TextView goods_comment;
        TextView good_dazhe;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tittle_shop_cancel:
                finish();
                break;
            default:
                break;
        }
    }

}
